package com.ffmpeg.util.infra.handle;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;

import javax.annotation.Resource;

import com.ffmpeg.util.infra.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;

/**
 * @author :wm
 * @description : ffmpeg执行器
 */
@Component
public class FfmpegHandle {
    private final static Logger logger = LoggerFactory.getLogger(FfmpegHandle.class);

    @Resource
    private TaskExecutor taskExecutor;

    public void executeProcess(ProcessBuilder processBuilder) {
        processBuilder.redirectErrorStream(true);
        try {
            //开始处理文件
            logger.info("start processing file");
            Date startDateTime = new Date();
            Process process = processBuilder.start();
            //防止线程阻塞
            final InputStream inputStream = process.getInputStream();
            taskExecutor.execute(() -> {
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                try {
                    while ((line = reader.readLine()) != null) {
                        logger.debug(line);
                    }
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            process.waitFor();
            Date endDateTime = new Date();
            //文件处理完成
            logger.info("file processing success, cost {} s", DateUtils.getCostValue(startDateTime, endDateTime));
        } catch (Exception e) {
            throw new RuntimeException("ffmpeg execute error" + e.getMessage());
        }
    }
}
